const path = require('path');

const csRenderBasePath = path.resolve('./packages/core/src/index');
const csToolsBasePath = path.resolve('./packages/tools/src/index');
const csAiBasePath = path.resolve('./packages/ai/src/index');
const csLabelmapInterpolationBasePath = path.resolve(
  './packages/labelmap-interpolation/src/index'
);
const csPolymorphicSegmentationBasePath = path.resolve(
  'packages/polymorphic-segmentation/src/index'
);
const csAdaptersBasePath = path.resolve('./packages/adapters/src/index');
const csDICOMImageLoaderDistPath = path.resolve(
  'packages/dicomImageLoader/src/index'
);
const csNiftiPath = path.resolve('packages/nifti-volume-loader/src/index');

module.exports = function buildConfig(names, exampleBasePaths, destPath, root) {
  let multiExampleEntryPoints = '';

  names.forEach((name, index) => {
    const exampleBasePath = exampleBasePaths[index];
    multiExampleEntryPoints += `${name.replace(
      /\\/g,
      '/'
    )}: "${exampleBasePath.replace(/\\/g, '/')}", \n`;
  });

  let multiTemplates = '';
  names.forEach((name) => {
    multiTemplates += `
      new rspack.HtmlRspackPlugin({
        title: '${name}',
        chunks: ['${name}'],
        filename: '${name}.html',
        template: '${root.replace(
          /\\/g,
          '/'
        )}/utils/ExampleRunner/template.html',
      }),`;
  });

  multiTemplates += '\n';

  return `
// THIS FILE IS AUTOGENERATED - DO NOT EDIT
const path = require('path')
const fs = require('fs');
const rules = require('./rules-examples.js');
const modules = [path.resolve('../node_modules/'), path.resolve('../../../node_modules/')];
const rspack = require('@rspack/core');

const dir = "${destPath.replace(/\\/g, '/')}";

if (!fs.existsSync(dir)){
    console.debug('Creating directory: ' + dir);
    fs.mkdirSync(dir);
}

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  plugins: [
    ${multiTemplates}
    new rspack.DefinePlugin({
      __BASE_PATH__: "''",
    }),
    new rspack.CopyRspackPlugin({
      patterns: [
        {
          from: '${root.replace(/\\/g, '/')}/utils/ExampleRunner/serve.json',
          to: "${destPath.replace(/\\/g, '/')}"
        },
        {
          from: '../../../node_modules/dicom-microscopy-viewer/dist/dynamic-import/',
          to: '${destPath.replace(/\\/g, '/') + '/dicom-microscopy-viewer/'}',
          noErrorOnMissing: true,
        },
        {
          from:
            '../../../node_modules/onnxruntime-web/dist',
          to: '${destPath.replace(/\\/g, '/')}/ort',
        },
      ],
    }),
    new rspack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    }),
  ],
  entry: {
    ${multiExampleEntryPoints}
  },
  output: {
    path: '${destPath.replace(/\\/g, '/')}',
    filename: '[name].js',
  },
  module: {
    rules,
  },
  experiments: {
    asyncWebAssembly: true,
    nativeWatcher: true,
  },
  externals: {
    "dicom-microscopy-viewer": {
      root: "window",
      commonjs: "dicomMicroscopyViewer",
    },
  },
  resolve: {
    alias: {
      '@cornerstonejs/core': '${csRenderBasePath.replace(/\\/g, '/')}',
      '@cornerstonejs/tools': '${csToolsBasePath.replace(/\\/g, '/')}',
      '@cornerstonejs/ai': '${csAiBasePath.replace(/\\/g, '/')}',
      '@cornerstonejs/polymorphic-segmentation': '${csPolymorphicSegmentationBasePath.replace(
        /\\/g,
        '/'
      )}',
      '@cornerstonejs/labelmap-interpolation': '${csLabelmapInterpolationBasePath.replace(
        /\\/g,
        '/'
      )}',
      '@cornerstonejs/adapters': '${csAdaptersBasePath.replace(/\\/g, '/')}',
      '@cornerstonejs/dicom-image-loader': '${csDICOMImageLoaderDistPath.replace(
        /\\/g,
        '/'
      )}',
      '@cornerstonejs/nifti-volume-loader': '${csNiftiPath.replace(
        /\\/g,
        '/'
      )}',
    },
    modules,
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    fallback: {
      fs: false,
      path: require.resolve('path-browserify'),
      events: false,
      buffer: require.resolve('buffer'),
    },
  },
  devServer: {
    hot: true,
    open: false,
    port: ${process.env.CS3D_PORT || 3000},
    historyApiFallback: true,
    allowedHosts: [
      '127.0.0.1',
      'localhost',
    ],
  },
  optimization: {
    minimize: false,
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
        commons: {
          test: /[\\/]packages[\\/]/,
          name: 'commons',
          chunks: 'all',
          minChunks: 2,
        },
      },
    }
  },
};
`;
};
